package com.ultrapower.ctool.xn_app;

import android.app.Notification;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ultrapower.ctool.ConfUtils;
import com.ultrapower.ctool.core.CustomApplication;
import com.ultrapower.ctool.db.SqlHelpDemo;
import com.ultrapower.ctool.http.HttpUtil;
import com.ultrapower.ctool.model.UserDO;
import com.ultrapower.ctool.utils.DialogDemo;
import com.ultrapower.ctool.utils.SerializableMap;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static android.R.attr.type;
import static android.provider.Telephony.Mms.Part.FILENAME;

public class LoginActivity extends AppCompatActivity {

    private static final int LOGIN_SUCCESS = 0;

    private static final int LOGIN_FAILED = 1;

    private static final int LOGIN_WRONG = 2;

    private static final String FILENAME = "xnaj_lo";

    private EditText username;//用户名

    private EditText password;//密码

    private Button loginButton;//登录按钮

    private ProgressDialog progressDialog;

    private CheckBox isRemeber;//记住密码

    private SharedPreferences sp;

    private String userInfo;

    private SerializableMap menu = new SerializableMap();
    private String login_path = ConfUtils.SERVICE_URL + "login/doLogin";
    //private OkHttpClient client = new OkHttpClient();
    private Gson gson = new Gson();
    private CustomApplication application;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case LOGIN_SUCCESS:
                    closeProgressDialog();
                    Intent intent = new Intent(LoginActivity.this, Main.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("menu", menu);
                    intent.putExtras(bundle);
                    intent.putExtra("userInfo", userInfo);
                    startActivity(intent);
                    finish();
                    break;
                case LOGIN_WRONG:
                    closeProgressDialog();
                    Toast.makeText(LoginActivity.this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
                    break;
                case LOGIN_FAILED:
                    closeProgressDialog();
                    Toast.makeText(LoginActivity.this, "网络繁忙,请稍后再试", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        username = (EditText) findViewById(R.id.username);
        password = (EditText) findViewById(R.id.password);
        loginButton = (Button) findViewById(R.id.loginbutton);
        isRemeber = (CheckBox)findViewById(R.id.checkbox);
        userInfo = username.getText().toString().trim();
        application = (CustomApplication) getApplication();
        isRemeber.setOnClickListener(new View.OnClickListener() {//记住密码
            @Override
            public void onClick(View v) {
                writeBoolean(isRemeber.isChecked());
            }
        });

        if (readBoolean("isRemeber")) {
            isRemeber.setChecked(true);
            username.setText(readData("username").toString());
            password.setText(readData("password").toString());
        }
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String userName = username.getText().toString().trim();    //获取当前输入的用户名和密码信息
                final String userPwd = password.getText().toString().trim();
                if (userName.equals("")) {
                    Toast.makeText(getApplicationContext(), "用户名不能为空", Toast.LENGTH_SHORT).show();
                } else if (userPwd.equals("")) {
                    Toast.makeText(getApplicationContext(), "密码不能为空", Toast.LENGTH_SHORT).show();
                } else {
                    writeData(userName, userPwd, isRemeber.isChecked());
                    showProgressDialog();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                OkHttpClient client = new OkHttpClient();
                                RequestBody requestBody = new FormBody.Builder()
                                        .add("loginId", userName)
                                        .add("loginPwd", userPwd)
                                        .build();
                                Request request = new Request.Builder().url(login_path).post(requestBody).build();
                                Response response = client.newCall(request).execute();
                                if (response.isSuccessful()) {//成功
                                    String result = response.body().string();
                                    Map<String, Map<String, Object>> resultMap = gson.fromJson(result, new TypeToken<Map<String, Map<String, Object>>>() {
                                    }.getType());
                                    if ((boolean) (resultMap.get("result").get("success"))) {
                                        menu.setMap((Map) (resultMap.get("result").get("menus")));
                                        UserDO user = gson.fromJson((resultMap.get("result").get("user")).toString(), new TypeToken<UserDO>() {
                                        }.getType());
                                        application.userLogin(user);
                                        application.setSerializableMap(menu);
                                        Message message = new Message();
                                        message.what = LOGIN_SUCCESS;
                                        handler.sendMessage(message);

                                    } else {//用户名密码错误
                                        Message message = new Message();
                                        message.what = LOGIN_WRONG;
                                        handler.sendMessage(message);
                                    }
                                } else {
                                    Message message = new Message();
                                    message.what = LOGIN_FAILED;
                                    handler.sendMessage(message);
                                }
                            } catch (IOException e) {
                                Message message = new Message();
                                message.what = LOGIN_FAILED;
                                handler.sendMessage(message);
                                e.printStackTrace();
                            }

                        }
                    }).start();

                }
            }
        });


    }

    private void writeBoolean(boolean isRemeber) {
        SharedPreferences.Editor share_edit = getSharedPreferences(FILENAME,
                MODE_MULTI_PROCESS).edit();
        share_edit.putBoolean("isRemeber", isRemeber);
        share_edit.commit();
    }

    private boolean readBoolean(String data) {
        SharedPreferences pref = getSharedPreferences(FILENAME, MODE_MULTI_PROCESS);
        return pref.getBoolean(data, false);
    }

    private String readData(String data) {
        SharedPreferences pref = getSharedPreferences(FILENAME, MODE_MULTI_PROCESS);
        String str = pref.getString(data, "");
        return str;
    }

    private boolean writeData(String userinfo, String password, boolean isRemeber) {
        SharedPreferences.Editor share_edit = getSharedPreferences(FILENAME,
                MODE_MULTI_PROCESS).edit();
        share_edit.putString("username", userinfo);
        share_edit.putString("password", password);
        share_edit.putBoolean("isRemeber", isRemeber);
        share_edit.commit();
        return true;
    }


    /**
     * 显示进度对话框
     */
    private void showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(LoginActivity.this);
            progressDialog.setMessage("正在加载，请稍等...");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }

    /**
     * 关闭进度对话框
     */
    private void closeProgressDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }
}
